package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

public class apiAutoGetMessage implements ServiceBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(apiAutoGetMessage.class)
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static Map<String, String> headMap = new HashMap<String, String>();
    private static boolean isRun = true;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8")
        response.setContentType("application/json;charset=UTF-8")
        long startTime = System.currentTimeMillis()

        try {

            String StartTime = request.getParameter("StartTime");
            String EndTime = request.getParameter("EndTime");
            String interval = request.getParameter("interval");
            int intervalMin = KHUtil.isNull(interval) ? 1000 : Integer.parseInt(interval);
            log.debug("doCallBack API StartTime:" + StartTime + " EndTime:" + EndTime + " 时间间隔interval:" + interval);

            // 获取当前日期
            Calendar StartTimeDefault = Calendar.getInstance();
            Calendar EndTimeDefault = Calendar.getInstance();
            StartTimeDefault.add(Calendar.DAY_OF_MONTH, -1);

            StartTime = KHUtil.isNull(StartTime) ? sdf.format(StartTimeDefault.getTime()) : StartTime;
            EndTime = KHUtil.isNull(EndTime) ? sdf.format(EndTimeDefault.getTime()) : EndTime;
            log.debug("同步记录数据 StartTime:" + StartTime + " EndTime:" + EndTime);

            // 获取数据源
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 同步普通短信
            int Offset = 1;
            isRun = true;
            log.debug("同步普通短信 获取云片短信发送历史...");
            while (isRun && Offset < 5000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("同步普通短信 获取云片短信发送历史...偏移Offset:" + Offset);
                toDoSMSGet(jt, StartTime, EndTime, Offset, KHDBConfig.getParamConfig(eliteBean, "YUNPIAN_TZ_apiKey"));
                Offset = Offset + 1;
            }
            log.debug("同步普通短信 获取云片短信发送历史 结束执行...");

            // 同步营销短信
            Offset = 1;
            isRun = true;
            log.debug("同步营销短信 获取云片短信发送历史...");
            while (isRun && Offset < 5000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("同步营销短信 获取云片短信发送历史...偏移Offset:" + Offset);
                toDoSMSGet(jt, StartTime, EndTime, Offset, KHDBConfig.getParamConfig(eliteBean, "YUNPIAN_YX_apiKey"));
                Offset = Offset + 1;
            }

            log.debug("同步营销短信 获取云片短信发送历史 结束执行...");
        } catch (Exception e) {
            log.error("HTTP请求调用错误，接口处理异常：" + e.getMessage());
            return e.getMessage();

        }

        return "success"
    }

    // 1-获取云片短信发送历史
    public static void toDoSMSGet(JdbcTemplate jt, String StartTime, String EndTime, int Offset, String apikey) throws Exception {

        Map<String, String> paramHashMap = new HashMap<String, String>();
        paramHashMap.put("apikey", apikey);
        paramHashMap.put("start_time", StartTime + " 00:00:00");
        paramHashMap.put("end_time", EndTime + " 23:59:59");
        paramHashMap.put("page_num", String.valueOf(Offset));
        paramHashMap.put("page_size", "100");

        String injson = SplicingMap(paramHashMap, "&");
        log.debug("获取云片短信发送历史 待发送参数信息:" + injson);

        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/x-www-form-urlencoded");
        Date date2 = new Date();
        String resTokenJson = Util.doHttpPostUseHead("https://sms.yunpian.com/v2/sms/get_record.json", injson, "UTF-8", 10000, 0, headMap);
        log.debug("获取云片短信发送历史 resTokenJson: " + resTokenJson);

        JSONArray sms_JSONArray = JSONArray.fromObject(resTokenJson);

        if (sms_JSONArray.size() < 100) {
            isRun = false;
        }

        for (int i = 0; i < sms_JSONArray.size(); i++) {

            JSONObject sms_Json = sms_JSONArray.getJSONObject(i);
            String sid = KHUtil.GetSFJV(sms_Json, "sid");
            String mobile = KHUtil.GetSFJV(sms_Json, "mobile");
            String send_time = KHUtil.GetSFJV(sms_Json, "send_time");
            String text = KHUtil.GetSFJV(sms_Json, "text");
            String send_status = KHUtil.GetSFJV(sms_Json, "send_status");
            String report_status = KHUtil.GetSFJV(sms_Json, "report_status");
            String fee = KHUtil.GetSFJV(sms_Json, "fee");
            String user_receive_time = KHUtil.GetSFJV(sms_Json, "user_receive_time") == "" ? null : KHUtil.GetSFJV(sms_Json, "user_receive_time");
            String error_msg = KHUtil.GetSFJV(sms_Json, "error_msg");
            String uid = KHUtil.GetSFJV(sms_Json, "uid");
            log.debug("获取云片短信发送历史 当前:" + sms_Json);

            String selectSQL = "Select Documentout_Guid From Documentout Where 1 = 1";
            List<Map<String, Object>> selectList = null;
            if (!KHUtil.isNull(uid)) {
                selectList = jt.queryForList(selectSQL + " And Uid = ?", uid);
            } else {
                selectList = jt.queryForList(selectSQL + " And MsgID = ?", sid);

            }
            String DOCTEMPLATE_ID = "";
            //模糊获取模板ID
            String doctemplatesql = '''Select Doctemplate_Id,
                                               If(Instr(Documentpath2, '#') > 0, Substr(Documentpath2, 1, Instr(Documentpath2, '#') - 1), Documentpath2) As Start_With,
                                               If(Instr(Documentpath2, '#') > 0,
                                                  Reverse(Left(Reverse(Documentpath2), Locate('#', Reverse(Documentpath2)) - 1)),
                                                  '') As End_With,
                                               Documentpath2
                                          From Doctemplate
                                         Where Doctype = 0
                                           And Apikey = ?'''
            List doctemplatelist = jt.queryForList(doctemplatesql, apikey);

            for (int j = 0; j < doctemplatelist.size(); j++) {
                String tDoctemplate_Id = doctemplatelist.get(j).getAt("Doctemplate_Id");
                String Start_With = doctemplatelist.get(j).getAt("Start_With");
                String End_With = doctemplatelist.get(j).getAt("End_With");
                String Documentpath2 = doctemplatelist.get(j).getAt("Documentpath2");

                if (!KHUtil.isNull(Start_With) && !KHUtil.isNull(End_With)) {
                    if (text.startsWith(Start_With) && text.endsWith(End_With)) {
                        DOCTEMPLATE_ID = tDoctemplate_Id;
                        break;
                    }
                } else if (!KHUtil.isNull(Start_With) && KHUtil.isNull(End_With)) {
                    if (text.startsWith(Start_With)) {
                        DOCTEMPLATE_ID = tDoctemplate_Id;
                        break;
                    }
                } else {
                    log.warn("未能识别到模板ID信息");

                }

            }

            if (doctemplatelist.size() > 0) {
                DOCTEMPLATE_ID = doctemplatelist.get(0).get("DOCTEMPLATE_ID");
            }

            if (selectList.size() <= 0) {
                String updateSQL = "Insert Into Documentout (Documentout_Guid, Doctype, Status, Trialcount, Trialcountlimit, Documentfrom, Documentto, Documentpath, Comments, Priority_Id, Expectedstartdate, Lasttrydatetime, Finishdatetime, Createdby, Createddate, Modifiedby, Modifieddate, MsgID, Uid, Report_Status, User_Receive_Time, Error_Detail, Synchronize_Time, Sub_Doctype,Template_Id) Values (Uuid(), 3, 1, 1, 3, 'IVR', ?, ?, ?, '0', Null, ?, ?, 'SELITE', ?, 'SELITE', Now(), ?, ?, ?, ?, ?, Now(), 'IVR', ?)";

                jt.update(updateSQL, mobile, text, "IVR", send_time, send_time, send_time, sid, uid, report_status, user_receive_time, error_msg, DOCTEMPLATE_ID);

            }

        }
    }

    // 参数处理
    public static String SplicingMap(Map<String, String> param, String Splicing) {
        TreeMap<String, String> paramTreeMap = new TreeMap<>(param);
        String prestr = "";
        for (Map.Entry<String, String> vo : paramTreeMap.entrySet()) {
            vo.getKey();
            vo.getValue();
            prestr = prestr + Splicing + vo.getKey() + "=" + vo.getValue();
        }
        prestr = prestr.substring(1);
        return prestr;
    }

}